﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace SampleTree
{
    public class Member
    {
        DataAccess _da = new DataAccess();


        public Member()
        {

        }


        public Member(string cn)
        {
            _da = new DataAccess(cn);
        }

        public DataRow GetMemberInfo(string id)
        {
            DataSet ds = _da.GetDataSet("get_memberInfo", id);
            if (ds != null)
            {
                if (ds.Tables[0].Rows.Count > 0)
                    return ds.Tables[0].Rows[0];
            }
            return null;
        }


        public DataSet GetMember(string txt)
        {
            return _da.GetDataSet("get_member", txt);
        }

        public List<MemberAgent> GetGeneology(string memberId)
        {
            List<MemberAgent> lst = new List<MemberAgent>();
            bool bFound = true;
            int iLevel = 1;
            List<string> sMembers = new List<string>();
            sMembers.Add(memberId);

            while (bFound)
            {
                string sql = "select * from member where agent in (" + inMembers(sMembers) + ")";
                DataSet ds = _da.GetDataSet(sql);
                StringBuilder sb = new StringBuilder();
                string AgentId = memberId;
                if (ds != null)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {

                        sMembers.Clear();
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            DataRow dr = ds.Tables[0].Rows[i];
                            string sortID = MemberSortID(i, iLevel, dr["agent"].ToString(), lst);
                            string sName = dr["Lastname"].ToString() + "," + dr["FirstName"].ToString() + " " + dr["Middlename"].ToString();
                            if (dr["Middlename"].ToString().Length == 1) sName += ".";
                            lst.Add(new MemberAgent { Level = iLevel, MemberID = dr["memberid"].ToString(), AgentID = dr["agent"].ToString(), Name = sName, SortID = sortID });
                            sMembers.Add(dr["memberid"].ToString());
                        }
                        iLevel++;
                        if (iLevel > 5) bFound = false;
                    }
                    else
                        bFound = false;
                }
                else
                    bFound = false;

            }

            return lst.OrderBy(c => c.SortID).ToList();
        }

        public string GetGeneologyTable(string id)
        {
            List<MemberAgent> lst = GetGeneology(id);
            if (lst != null)
            {
                if (lst.Count > 0)
                {
                    string tbl = @"     <table id=""treetbl"">
        <thead><tr><th>Member</th><th>Level</th></tr></thead>
        <tbody>
          @@tablebody@@
        </tbody>
      </table>";

                    string hdrlevel = @"          <tr data-tt-id=""@@id@@"">
            <td>@@id@@-@@name@@</td>
            <td>1</td>
          </tr>";

                    string othlevel = @"<tr data-tt-id=""@@id@@"" data-tt-parent-id=""@@idparent@@"">
            <td>@@id@@-@@name@@</td>
            <td>@@level@@</td>
          </tr>";


                    StringBuilder sb = new StringBuilder();
                    foreach (MemberAgent ma in lst)
                    {
                        if (ma.Level == 1)
                            sb.Append(hdrlevel.Replace("@@id@@", ma.MemberID).Replace("@@name@@", ma.Name));
                        else
                            sb.Append(othlevel.Replace("@@id@@", ma.MemberID).Replace("@@idparent@@", ma.AgentID).Replace("@@level@@", ma.Level.ToString()).Replace("@@name@@", ma.Name));
                    }

                    return tbl.Replace("@@tablebody@@", sb.ToString());
                }
            }
            return "No record!";
        }

        private string MemberSortID(int iCnt, int iLevel, string id, List<MemberAgent> members)
        {
            string sRet = iCnt.ToString("000");
            if (iLevel == 1) return sRet;
            try
            {
                return members.Find(c => c.MemberID == id).SortID + "-" + sRet;
            }
            catch
            {
                return iCnt.ToString("000");
            }

        }


        private string inMembers(List<string> members)
        {
            if (members != null)
            {
                StringBuilder sb = new StringBuilder();
                int i = 0;
                foreach (string s in members)
                {
                    sb.Append(((i != 0) ? "," : "") + "'" + s + "'");
                    i++;
                }
                return sb.ToString();
            }
            return "";
        }


        public DataSet GetDirectEarning(string id)
        {
            return _da.GetDataSet("get_directEarning", id);
        }

        public DataSet GetUnilevelEarning(string id)
        {
            return _da.GetDataSet("get_unilevelEarning", id);
        }


        public DataSet GetDirectSummary(DateTime? dtFrom, DateTime? dtTo)
        {
            return _da.GetDataSet("get_directSummary", dtFrom, dtTo);
        }

        public DataSet GetUnilevelSummary(DateTime? dtFrom, DateTime? dtTo)
        {
            return _da.GetDataSet("get_unilevelSummary", dtFrom, dtTo);
        }



        public DataSet GetDirectSummary_detail(string memberid, DateTime? dtFrom, DateTime? dtTo)
        {
            return _da.GetDataSet("get_directSummaryDet", dtFrom, dtTo);
        }


        public DataSet GetUnilevelSummary_detail(string memberid, DateTime? dtFrom, DateTime? dtTo)
        {
            return _da.GetDataSet("get_unilevelSummaryDet", dtFrom, dtTo);
        }


        public DataTable GetForProcess(DateTime? dtFrom, DateTime? dtTo)
        {
            try
            {
                return _da.GetDataSet("get_forProcess", dtFrom, dtTo).Tables[0];
            }
            catch
            {
                return null;
            }
        }

        public void Process(string memberid)
        {
            List<MemberAgent> lst = new List<MemberAgent>();
            bool bFound = true;
            int iLevel = 1;
            string sMem = memberid;

            while (bFound)
            {
                string sql = "select * from member where memberid  = '" + sMem.Replace("'", "''") + "'";
                DataRow dr = _da.GetDataRow(sql);

                if (dr != null)
                {
                    string sqlInsert = "insert into memberlevel(memberid,agentid, level) select '@memberid@', '@agentid@', @level@";


                    //insert data into memberleveltable
                    _da.ExecuteSQL(sqlInsert.Replace("@memberid@", memberid).Replace("@agentid@", dr["agent"].ToString()).Replace("@level@", iLevel.ToString()));
                    iLevel++;
                }
                else
                    bFound = false;

            }

            //Process Member
            _da.ExecuteNonQuery("Process_Member", memberid);

        }


        public void Process(List<string> memberids)
        {
            foreach (string mem in memberids)
                Process(mem);
        }

    }

    public class MemberAgent
    {
        public string SortID { get; set; }
        public string AgentID { get; set; }
        public string MemberID { get; set; }
        public string Name { get; set; }
        public int Level { get; set; }
        public int CLevel { get; set; }
    }
}
